@attribute [Authorize(Roles="Employee")]
@inherits AppAuthComponentBase

<form @onsubmit="submit">
<CascadingValue Value=@api.Error>
<div class=@ClassNames("shadow overflow-hidden sm:rounded-md bg-white dark:bg-black", @class)>
    
    <div class="relative px-4 py-5 bg-white dark:bg-black sm:p-6">

        <CloseButton OnClose="close" />

        <fieldset>
            <legend class="text-base font-medium text-gray-900 dark:text-gray-50 text-center mb-4">Edit Booking</legend>

            <ErrorSummary Except=@VisibleFields />
            <ErrorSummary ExplicitStatus=@deleteApi.Error />

            <div class="grid grid-cols-6 gap-6">
                <div class="col-span-6 sm:col-span-3">
                    <TextInput @bind-Value="request.Name" required placeholder="Name for this booking" />
                </div>

                <div class="col-span-6 sm:col-span-3">
                    <SelectInput @bind-Value="request.RoomType" Options=@(Enum.GetValues<RoomType>().Cast<RoomType?>()) /> 
                </div>

                <div class="col-span-6 sm:col-span-3">
                    <TextInput type="number" @bind-Value="request.RoomNumber" min="0" required />
                </div>

                <div class="col-span-6 sm:col-span-3">
                    <TextInput type="number" @bind-Value="request.Cost" min="0" required />
                </div>

                <div class="col-span-6 sm:col-span-3">
                    <DateTimeInput @bind-Value="request.BookingStartDate" required />
                </div>
                <div class="col-span-6 sm:col-span-3">
                    <DateTimeInput @bind-Value="request.BookingEndDate" />
                </div>
    
                <div class="col-span-6">
                    <TextAreaInput @bind-Value="request.Notes" placeholder="Notes about this booking" style="height:6rem" />
                </div>
            </div>
        </fieldset>
    </div>

    <div class="mt-4 px-4 py-3 bg-gray-50 dark:bg-gray-900 text-right sm:px-6">
        <div class="flex justify-between items-center">
            <div>
                <ConfirmDelete OnDelete="delete">Delete</ConfirmDelete>
            </div>
            <SrcLink href="https://github.com/NetCoreTemplates/blazor-tailwind/blob/master/MyApp.Client/Pages/BookingsCrud/Edit.razor" 
                     IconSrc="/img/blazor.svg" class="mt-2" />
            <div>
                <PrimaryButton type="submit">
                    Update Booking
                </PrimaryButton>
            </div>
        </div>
    </div>

</div>

</CascadingValue>
</form>


@if (api.Succeeded) {
    <h3 class="text-success mt-4">@api.Response!.Id</h3>
}

@code {
    [Parameter] public int? Id { get; set; }
    [Parameter] public EventCallback<IdResponse> done { get; set; }

    // Hide Error Summary Messages for Visible Fields which displays contextual validation errors
    string[] VisibleFields => new[] {
        nameof(request.Name),
        nameof(request.RoomType),
        nameof(request.RoomNumber),
        nameof(request.BookingStartDate),
        nameof(request.BookingEndDate),
        nameof(request.Cost),
        nameof(request.Notes),
    };
    
    UpdateBooking request = new();

    async Task refresh()
    {
        var selectApiResult = await ApiAsync(new QueryBookings { Id = Id });
        if (selectApiResult.Failed)
        {
            api = ApiResult.CreateError<IdResponse>(selectApiResult.Error!);
            return;
        }

        if (selectApiResult.Response!.Results.Count == 0)
        {
            api = ApiResult.CreateError<IdResponse>($"Booking #{Id} does not exist");
            return;
        }

        var booking = selectApiResult.Response!.Results[0];
        request = new UpdateBooking
        {
            Id = booking.Id,
            Name = booking.Name,
            RoomType = booking.RoomType,
            RoomNumber = booking.RoomNumber,
            BookingStartDate = booking.BookingStartDate,
            BookingEndDate = booking.BookingEndDate,
            Cost = booking.Cost,
            Notes = booking.Notes,
        };
    }

    protected override async Task OnInitializedAsync() => await refresh();

    async Task close() => await done.InvokeAsync(null);

    ApiResult<IdResponse> api = new();

    async Task submit()
    {
        api = await ApiAsync(request);

        if (api.Succeeded)
        {
            await done.InvokeAsync(api.Response!);
        }
    }

    ApiResult<EmptyResponse> deleteApi = new();

    async Task delete()
    {
        deleteApi = await ApiAsync(new DeleteBooking { Id = Id ?? 0 });

        if (deleteApi.Succeeded)
            await close();
    }
}
